//
//  WebController.m
//  Fhc
//
//  Created by steve aa on 14-8-12.
//  Copyright (c) 2014年 Alex. All rights reserved.
//

#import "WebController.h"
#import "WWSideViewController.h"
#import "XXTool.h"

#import "RXMLExhibitorInformationModel.h"
#import "ExhibitorsDetailsViewController.h"

@interface WebController ()<UIWebViewDelegate,UIAlertViewDelegate>

@property (nonatomic,strong) UIWebView *webView;
@property (nonatomic,strong) UIActivityIndicatorView *loading;

@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) DKButton *closeButton;

@property (nonatomic, assign) BOOL isErrorShow;

@end

@implementation WebController

-(UIWebView*)webView
{
    if (_webView==nil)
    {
        _webView = [[UIWebView alloc] init];
        _webView.backgroundColor = [UIColor whiteColor];
        [_webView setDelegate:self];
        [_webView setScalesPageToFit:YES];
        [self.view addSubview:_webView];
    }
    return _webView;
}

-(UIActivityIndicatorView*)loading
{
    if (_loading==nil)
    {
        _loading = [[UIActivityIndicatorView alloc] init];
        [_loading setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
        [_loading setHidesWhenStopped:YES];
        [self.view addSubview:_loading];
    }
    return _loading;
}

-(UILabel*)titleLabel
{
    if (_titleLabel == nil)
    {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.hidden = YES;
        _titleLabel.backgroundColor = [XXTool colorWithProject];
        _titleLabel.font = [UIFont systemFontOfSize:13];
        _titleLabel.numberOfLines = 0;
        [self.view addSubview:_titleLabel];
    }
    return _titleLabel;
}

-(DKButton*)closeButton
{
    if (_closeButton == nil)
    {
        _closeButton = [[DKButton alloc] init];
        _closeButton.hidden = YES;
        _closeButton.image = [UIImage imageNamed:@"会刊详情关闭按钮"];
        [_closeButton setColor:[UIColor clearColor] ForState:DKButtonStateNormal];
        _closeButton.imageRenderingMode = DKButtonRenderingModeAlwaysOriginal;
        _closeButton.imageSize = CGSizeMake(40, 40);
        [_closeButton addTarget:self Select:@selector(onTapClose) ForEvent:DKButtonEventPressedEnd];
        [self.view addSubview:_closeButton];
    }
    return _closeButton;
}

-(void)setRequest:(NSString *)request
{
    if (_type==WebControllerHallShowMapUse)
    {
        _request = request;
    }
    else
    {
        if ([request rangeOfString:@"http://"].location==NSNotFound && [request rangeOfString:@"https://"].location == NSNotFound)
        {
            request = [NSString stringWithFormat:@"http://%@",request];
        }
        _request = request;
    }
    
}

-(void)setType:(WebControllerType)type
{
    _type = type;
    if (_type==WebControllerRootVC)
    {
        [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"更多"] style:UIBarButtonItemStylePlain target:self action:@selector(clickleft)]];
    }
}

-(void)refreshLayout:(CGRect)frame
{
    self.webView.frame = CGRectMake(0, 0, frame.size.width
                                , frame.size.height);
    self.loading.frame = CGRectMake((frame.size.width-100)/2
                                , (frame.size.height-100)/2
                                , 100
                                , 100);
    self.titleLabel.frame = CGRectMake(0
                                       , frame.size.height-60
                                       , frame.size.width
                                       , 60);
    self.closeButton.frame = CGRectMake(frame.size.width - 40 - 3
                                        , self.titleLabel.xx_origin.y+(self.titleLabel.xx_height - 40)/2
                                        , 40
                                        , 40);
}

-(void)webViewDidStartLoad:(UIWebView *)webView
{
    [self.navigationItem setTitle:NSLocalizedString(@"加载中...", nil)];
    [self.loading startAnimating];//播放加载动画
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    if (_navTit!=nil)
    {
        [self.navigationItem setTitle:_navTit];
    }
    else if (![[webView stringByEvaluatingJavaScriptFromString:@"document.title"] isEqualToString:@""])
    {
        [self.navigationItem setTitle:[webView stringByEvaluatingJavaScriptFromString:@"document.title"]];
    }
    else
    {
        [self.navigationItem setTitle:@""];
    }
    [self.loading stopAnimating];
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    if (_type==WebControllerInfoMapUse)
    {
       // NSLog(@"Map Fail");
    }
    else
    {
        if (!_isErrorShow)
        {
            _isErrorShow = YES;
            UIAlertView* hint=[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"提示", nil)
                                                         message:NSLocalizedString(@"网页加载失败", nil)
                                                        delegate:self
                                               cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                               otherButtonTitles:nil, nil];
            [hint show];
        }
        [self.navigationItem setTitle:NSLocalizedString(@"加载失败", nil)];
    }
    [self.loading stopAnimating];
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *urlString = [[request URL] absoluteString];
    NSRange range = [urlString rangeOfString:@"targetID"];
    if (range.location != NSNotFound)
    {
        NSString *exhibitorNo = [urlString substringFromIndex:range.location+range.length+1];
        RLMResults *exhibitor = [RXMLExhibitorInformationModel objectsInRealm:[RLMRealm realmWithPath:[XXTool dataBasePath]] where:[NSString stringWithFormat:@"StandNo = '%@'",exhibitorNo]];
        if (exhibitor.count>0) //该展位号有对应展商
        {
            if (self.titleLabel.hidden)
            {
                [ExhibitorsDetailsViewController pushViewControllerWithSourceVC:self exhibitorInfo:exhibitor[0]];
            }
        }
        return NO;
    }
    return YES;
}

-(void)clickleft
{
    //[self.navigationController.sideViewController showLeftView];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        _isErrorShow = NO;
    }
}

#pragma mark aciton
-(void)onTapClose
{
    self.titleLabel.hidden = YES;
    self.closeButton.hidden = YES;
}

#pragma mark api
-(void)refreshWebViewWithRequestString:(NSString *)request
{
    if (request == nil)
    {
        return;
    }
    if (_type==WebControllerHallShowMapUse)
    {
        NSURL *url = [NSURL fileURLWithPath:request];
        NSString* urlString = [NSString stringWithFormat:@"%@?id=%@",[url absoluteString],self.signID];
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
    }
    else
    {
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:request] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10]];
    }
}

-(void)refreshContentViewHiddenState:(BOOL)isHidden title:(NSString *)title
{
    self.titleLabel.hidden = isHidden;
    self.closeButton.hidden = isHidden;
    self.titleLabel.text = title;
}

+(void)pushWebControllerWithSourceVC:(UIViewController *)sourceVC requestString:(NSString *)request
mapTitle:(NSString*)title
{
    WebController *vc = [[WebController alloc] init];
    [vc setRequest:request];
    vc.navTit = title;
    [vc refreshWebViewWithRequestString:vc.request];
    if (sourceVC)
    {
        [sourceVC.navigationController pushViewController:vc animated:YES];
    }
}

+(void)pushWebControllerWithSourceVC:(UIViewController *)sourceVC
                       requestString:(NSString *)request
                             mapType:(WebControllerType)type
                            mapTitle:(NSString*)title
                              signID:(NSString *)sign
                             Company:(NSString *)cname
{
    WebController *vc = [[WebController alloc] init];
    vc.type = type;
    vc.request = request;
    vc.navTit = title;
    vc.signID = sign;
    vc.cname=cname;
    [vc refreshWebViewWithRequestString:vc.request];
    if (sourceVC)
    {
        [sourceVC.navigationController pushViewController:vc animated:YES];
    }
}

+(void)pushWebControllerWithSourceVC:(UIViewController *)sourceVC
                    isNeedTitleLabel:(BOOL)isNeed
                       requestString:(NSString *)request
                             mapType:(WebControllerType)type
                            mapTitle:(NSString *)title
                              signID:(NSString *)sign
                             boothNo:(NSString *)bootNo
                             Company:(NSString *)cname
{
    WebController *vc = [[WebController alloc] init];
    vc.type = type;
    vc.navTit = title;
    vc.signID = sign;
    vc.cname=cname;
    vc.request = request;
    [vc refreshWebViewWithRequestString:vc.request];
    [vc refreshContentViewHiddenState:!isNeed title:[NSString stringWithFormat:@"   %@\n   %@",bootNo,cname]];
    
    if (sourceVC)
    {
        [sourceVC.navigationController pushViewController:vc animated:YES];
    }
}

@end
